#include<iostream>
#include<vector>
#include<deque>
#include<string>
#include<algorithm>
#include<unordered_set>
using namespace std;


struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x):val(x), left(nullptr), right(nullptr){}
};

class Solution{
    private:
    vector<int> val;

    public:
    int ans1(TreeNode* root, int k){
        frontorder(root);
        sort(val.begin(), val.end());
        return val[k-1];

    }

    void frontorder(TreeNode* root){
        if(root == nullptr){
            return;
        }
        val.push_back(root->val);
        frontorder(root->left);
        frontorder(root->right);
    }

};

TreeNode* createTree(vector<int>& num, int index, int len){
    if(num[index] == '#'){
        return NULL;
    }
    TreeNode* root = new TreeNode(num[index]);

    if(index * 2 + 1 < len){
        root->left = createTree(num, index * 2 + 1, len);
    }else{
        root->left = nullptr;
    }
    if(index * 2 + 2 < len){
        root->right = createTree(num, index * 2 + 2, len);
    }else{
        root->right = nullptr;
    }

    return root;
}


void test1(){
    vector<int> num = {3,1,4,'#',2};
    TreeNode* root = createTree(num, 0, num.size());

    Solution s;
    int k = 1;
    int ret = s.ans1(root, k);
    cout << ret << endl;
    
}

void test2(){
    vector<int> num = {5,3,6,2,4,'#','#',1};
    TreeNode* root = createTree(num, 0, num.size());

    Solution s;
    int k = 3;
    int ret = s.ans1(root, k);
    cout << ret << endl;
    
}


int main(void){
    test1();
    cout << "-----------------------------" << endl;
    test2();

    return 0;
}